#!/usr/bin/python
# -*- coding: utf-8 -*-

#生成   a-z A-Z 0-9的样本

#首先做一个映射表
#对常见的几种英文字体生成就行了 （其实后期可以在加的）
#生成策略目前只考虑， 斜体、粗体、字号、位置  4中情况
#要使用多进程，为了高效率

#借鉴别人的思路，标签就是文件夹名字，样本放文件夹中     先用这种吧，毕竟数据量也不大，先从简单的角度来搞搞
#使用pandas之类的工具，其实这种方式效率肯定高一些的。。。


#必须要用多种字体试试！！！！！！！


#这个程序只考虑一个大小，水平方向上缩放一下！！！！



import numpy as np
import cv2
import os
import random
import my_ascll_dict
from PIL import Image,ImageFont,ImageDraw
import shutil
from multiprocessing import Pool,Lock
import time
import h5py




import win32con, win32file, pywintypes

LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # The default value
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
__overlapped = pywintypes.OVERLAPPED(  )

def lock(file, flags):
    hfile = win32file._get_osfhandle(file)
    win32file.LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped)

def unlock(file):
    hfile = win32file._get_osfhandle(file)
    win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)



OUTDIR = r'c:\Users\he\Desktop\d1'



#获取tmp的文件名到数组中
def get_file_list(path):
    list_name=[]
    files = os.listdir(path)
    files.sort()
    for file in files:
        file_path = os.path.join(path, file)
        list_name.append(file_path)
    return list_name





def generate_dataset(onechar):
    #os.mkdir(OUTDIR + "/%d" % onechar)

    #print('now generate %d index...' % onechar)
    index = 1

    npimgsets = []


    for fontfile in fontfilelist:
        for fonesize in range(18,28):
            ft = ImageFont.truetype(fontfile, fonesize)

            # 获取当前字体真实的位置和大小
            x, y = ft.getoffset(dicta[onechar])
            w, h = ft.getsize(dicta[onechar])

            for canvawith in range(12,28,1):

                # 随机生成位置，保证文字不到图片外面
                maxhorizontal = canvawith - w
                maxvertical = 28 - h

                for i in range(maxhorizontal):
                    for j in range(maxvertical):
                        # 获取pil的绘图对象
                        black = Image.new("RGB", [canvawith, 28], "black")
                        drawobj = ImageDraw.Draw(black)

                        drawobj.text((i - x, j - y), dicta[onechar], font=ft, fill='white')



                        if MODE == 'debug':
                            black.save(OUTDIR + "/%d.png" % (index))

                        black = black.resize(size=(28, 28))
                        #直接生成灰度图
                        black = black.convert('L')



                        index += 1
                        npimg = np.array(black)
                        npimgsets.append(npimg)

    if MODE != 'debug':
        #写入到文件
        print('%s：%d'%(dicta[onechar],len(npimgsets))  )

        ff = open('h5file.lock','a')
        lock(ff.fileno(), LOCK_EX)
        with h5py.File('number.h5','a') as f:
            f.create_dataset(dicta[onechar],data=npimgsets)


        unlock(ff.fileno())
        ff.close()

# 获取标签-实际字符映射表
dicta = my_ascll_dict.getmyasclldict()
print(dicta)

# 获取所有的字体文件
fontfilelist = get_file_list('./font')
print(fontfilelist)



MODE = 'debug'
#MODE = 'release'


if __name__ == '__main__':
    t1 = time.clock()

    # try:
    #     shutil.rmtree(OUTDIR)
    # except:
    #     print('errr')
    #
    # os.mkdir(OUTDIR)

    if MODE != 'debug':

        pool = Pool()
        pool.map(generate_dataset,dicta)
        pool.close()
        pool.join()
    else:
        for x in dicta:
            generate_dataset(x)
            break

    t2 = time.clock()
    print(t2-t1)





